package edu.ynu.se.xiecheng.achitectureclass.Demo1.service;

import edu.ynu.se.xiecheng.achitectureclass.Demo1.dao.DeviceDataDao;
import edu.ynu.se.xiecheng.achitectureclass.Demo1.entity.DeviceData;
import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

public abstract class DeviceDataService extends LogicService<DeviceDataDao, DeviceData, Long> {

    private final AccessTokenService accessTokenService;
    private final RestTemplate restTemplate;

    public DeviceDataService(DeviceDataDao deviceDataDao, AccessTokenService accessTokenService, RestTemplate restTemplate) {
        super(deviceDataDao);
        this.accessTokenService = accessTokenService;
        this.restTemplate = restTemplate;
    }

    public void fetchAndSaveData(String accessToken) {
        String url = "https://fbox360.com/api/v2/dmon/value/get?boxNo=300023040198";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + accessToken);
        headers.set("Content-Type", "application/json");

        // 设备 IDs 确保来自实现类
        List<String> deviceIds = getDeviceIds();
        Map<String, List<String>> requestBody = Map.of("ids", deviceIds);

        // 在发送请求前打印消息体
        System.out.println("请求的消息体: " + requestBody);

        HttpEntity<Map<String, List<String>>> request = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<List> response = restTemplate.postForEntity(url, request, List.class);

            // 输出返回的响应信息到控制台
            System.out.println("获取到的数据: " + response.getBody());

            // 解析响应数据并保存
            List<Map<String, Object>> dataList = response.getBody();
            if (dataList != null) {
                for (Map<String, Object> data : dataList) {
                    saveRealTimeData(data); // 调用保存方法
                }
            }
        } catch (Exception e) {
            System.err.println("数据获取失败：" + e.getMessage());
        }
    }

    protected void saveRealTimeData(Map<String, Object> realTimeData) {
        DeviceData data = createNewDataInstance();
        try {
            data.setName(realTimeData.get("name").toString());
            data.setValue(Double.parseDouble(realTimeData.get("value").toString()));
            data.setUnit(getUnit());
            data.setCreatedTime(LocalDateTime.now());

            // 保存数据
            getDAO().save(data);

            // 打印中文调试信息
            System.out.println("已保存数据: 名称=" + data.getName() + ", 值=" + data.getValue() + ", 单位=" + data.getUnit() + ", 创建时间=" + data.getCreatedTime());
        } catch (NumberFormatException e) {
            System.err.println("解析值失败: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("保存数据失败: " + e.getMessage());
        }
    }



    public List<DeviceData> getHistoryData(String dataType) {
        return getDAO().findByDataType(dataType);
    }

    protected abstract List<String> getDeviceIds();

    protected abstract DeviceData createNewDataInstance();

    protected abstract String getUnit();
}
